package com.token.iot.bratterycharging.boss.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.outstanding.framework.base.OutstandingService;
import com.outstanding.framework.base.transaction.OutstandingTransactionCallback;
import com.outstanding.framework.base.transaction.OutstandingTransactionTemplate;
import com.outstanding.framework.bootstrap.SystemPropertyConfigure;
import com.outstanding.framework.core.PendingException;
import com.outstanding.framework.core.ReturnCode;
import com.outstanding.framework.core.SysCode;
import com.token.batterycharging.account.api.AccountDTO;
import com.token.batterycharging.account.api.AccountFacade;
import com.token.batterycharging.account.api.AccountType;
import com.token.batterycharging.account.api.RealTimeFlag;
import com.token.batterycharging.account.api.RuleType;
import com.token.batterycharging.trade.api.FeeFacade;
import com.token.batterycharging.trade.api.FeeRuleDTO;
import com.token.batterycharging.trade.api.RuleDTO;
import com.token.iot.bratterycharging.boss.dao.AgentDAO;
import com.token.iot.bratterycharging.boss.web.AgentHelper;
import com.token.iot.bratterycharging.boss.web.Agents;
import com.token.iot.bratterycharging.boss.web.Merchant;
import com.token.iot.bratterycharging.boss.web.ResCode;

@Service
public class AgentsService extends OutstandingService {
	/**
	 * 强制事务（需要转移控制权的）
	 */
	@Autowired
	protected OutstandingTransactionTemplate forceTransactionTemplate;

	@Autowired
	private AgentDAO agentsDao;

	@Reference(version = "1.0.0")
	private AccountFacade facade;

	@Reference(version = "1.0.0")
	private FeeFacade feecade;

	public static String weixinPIN = SystemPropertyConfigure.getProperty("wechat.mchid");

	public static String shuakaPIN = SystemPropertyConfigure.getProperty("shuaka.pin");

	public static String pingtaiPIN = SystemPropertyConfigure.getProperty("pingtai.pin");

	public String saveNotNull(Agents value, Long operid) throws PendingException {
		AgentHelper helper = new AgentHelper(value);
		helper.validateForSave();
		// 有控制权的
		ReturnCode result = forceTransactionTemplate.execute(new OutstandingTransactionCallback<ReturnCode>() {
			// 先调用账户系统，创建对应的代理商账户
			/**
			 * 此方法必须抛出PendingException异常
			 */
			@Override
			public ReturnCode doInTransaction(TransactionStatus status) throws PendingException {
				String mobile = value.getAgentMobile();
				debug("the input mobile " + mobile);
				agentsDao.insertAgents(value);
				long userPIN = value.getId();
				debug("新建代理商的id" + value.getId());
				AccountDTO dto = new AccountDTO();
				dto.setUserPIN(String.valueOf(value.getId()));
				dto.setOperPIN(String.valueOf(operid));
				dto.setUserName(value.getName());
				// 创建账户
				facade.creatAccount(dto);

				FeeRuleDTO frdto = new FeeRuleDTO();
				frdto.setChannelPIN(weixinPIN);
				frdto.setRealTimeFlag(RealTimeFlag.direct);
				frdto.setUserPIN(String.valueOf(userPIN));
				frdto.setRuleType(RuleType.ratio);
				frdto.setRuleName("微信支付");
				// 两个渠道的账户编号
				List<RuleDTO> dtos = new ArrayList();
				RuleDTO merchant = new RuleDTO();
				merchant.setUserPIN(String.valueOf(userPIN));
				merchant.setValue(String.valueOf(value.getAgentOnlinepPercent()));
				merchant.setRuleName("代理商分润");
				dtos.add(merchant);

				RuleDTO pingtai = new RuleDTO();
				pingtai.setUserPIN(pingtaiPIN);
				pingtai.setValue(String.valueOf(10000 - value.getAgentOnlinepPercent()));
				pingtai.setRuleName("平台分润");
				dtos.add(pingtai);

				// 设置分润比列
				feecade.addFee(frdto, dtos);

				FeeRuleDTO frdto1 = new FeeRuleDTO();
				frdto1.setChannelPIN(shuakaPIN);
				frdto1.setRealTimeFlag(RealTimeFlag.direct);
				frdto1.setUserPIN(String.valueOf(userPIN));
				frdto1.setRuleType(RuleType.ratio);
				frdto1.setRuleName("刷卡支付");
				// 两个渠道的账户编号
				List<RuleDTO> dtos1 = new ArrayList();
				RuleDTO merchant1 = new RuleDTO();
				merchant1.setUserPIN(String.valueOf(userPIN));
				merchant1.setValue(String.valueOf(value.getAgentCoinsPercent()));
				merchant1.setRuleName("代理商分润");
				dtos1.add(merchant1);

				RuleDTO pingtai1 = new RuleDTO();
				pingtai1.setUserPIN(pingtaiPIN);
				pingtai1.setValue(String.valueOf(10000 - value.getAgentCoinsPercent()));
				pingtai1.setRuleName("平台分润");
				dtos1.add(pingtai1);

				// 设置分润比列
				feecade.addFee(frdto1, dtos1);

				return SysCode.SUCCESS;
			}
		});

		if (!SysCode.isSuccess(result)) {
			throw new PendingException(ResCode.AgentAccountCreatError);
		}
		return String.valueOf(result);
	}
	
	
	public PageInfo list(int pageNo, int pageSize) throws PendingException {
		// 注入插件参数
		PageHelper.startPage(pageNo, pageSize);
		// 执行sql
		List<Agents> list = agentsDao.list();
		PageInfo pageInfo = new PageInfo(list);
		return pageInfo;

	}
	
	
	
	public Agents detail(String agentid)throws PendingException {
		Agents agent= agentsDao.selectOneById(agentid);
		if(agent == null) {
			throw new PendingException(ResCode.AgentNotFind);
		}
		List<AccountDTO>  accounts = facade.selectByUserPIN(String.valueOf(agent.getId()));
		for(AccountDTO ac:accounts) {
			if(AccountType.CASH == ac.getAccountType()) {
				agent.setCash(ac.getBalance());
			}
			if(AccountType.SETTLE == ac.getAccountType()) {
				agent.setSettle(ac.getBalance());
			}
			if(AccountType.CASH == ac.getAccountType()) {
				agent.setTransit(ac.getBalance());
			}
		}
		
		List<FeeRuleDTO> dtos =feecade.selectFeeByUserPIN(String.valueOf(agent.getId()));
		for(FeeRuleDTO dto:dtos) {
			//微信
			if(weixinPIN.equals(dto.getChannelPIN())) {
				List<RuleDTO> rds = dto.getRules();
				for(RuleDTO rd:rds) {
					if(!pingtaiPIN.equals(rd.getUserPIN())) {
						agent.setAgentOnlinepPercent(Long.parseLong(rd.getValue()));
						break;
					}
					
				}
			}
			if(shuakaPIN.equals(dto.getChannelPIN())) {
				List<RuleDTO> rds = dto.getRules();
				for(RuleDTO rd:rds) {
					if(!pingtaiPIN.equals(rd.getUserPIN())) {
						agent.setAgentCoinsPercent(Long.parseLong(rd.getValue()));
						break;
					}
					
				}
			}
		}
		
		return agent;
	}
	
	
	
	
	public List<Agents> listall() throws PendingException {
		// 执行sql
		List<Agents> list = agentsDao.list();
		return list;

	}
	
	
	public Agents selectByUserNamePassword(String userName, String password) throws PendingException{
		return agentsDao.selectByUserNamePassword(userName, password);
	}
}
